﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using BusinessTier.MazeGenService;

namespace BusinessTier
{
    /// <summary>
    /// Maze server class.
    /// </summary>
    public class MazeServer
    {
        private IDictionary<string, Player> players;
        private string gameUid;

        public delegate void EventHappened(GameEvent e);
        public event EventHappened eventHappened;

        /// <summary>
        /// Read-only property containing a list of all of the usernames of
        /// players registered to this MazeServer instance.
        /// </summary>
        public IEnumerable<string> Users { get { return players.Keys; } }

        /// <summary>
        /// The read-only unique identifier of this game instance. This should
        /// be managed by the corresponding factory class in order to ensure
        /// that the IDs returned are in fact unique.
        /// </summary>
        public string Id { get { return gameUid; } }

        /// <summary>
        /// Constructs a new maze server instance with the given uid.
        /// </summary>
        /// <param name="gameUid"></param>
        public MazeServer(string gameUid)
        {
            this.gameUid = gameUid;
            this.players = new Dictionary<string, Player>();
        }

        /// <summary>
        /// Broadcasts the event that is passed in by calling the handlers
        /// attached to this maze server instance.
        /// </summary>
        /// <param name="e"></param>
        public void OnEventHappened(GameEvent e)
        {
            EventHappened handler = eventHappened;
            if (handler != null)
            {
                handler(e);
            }
        }

        /// <summary>
        /// Adds a player to this maze server instance.
        /// </summary>
        /// <param name="player"></param>
        public void addPlayer(Player player)
        {
            if (!players.ContainsKey(player.Username))
            {
                players.Add(player.Username, player);
            }
        }

        /// <summary>
        /// Removes a player from this maze server instance.
        /// </summary>
        /// <param name="username"></param>
        public void removePlayer(string username)
        {
            if (players.ContainsKey(username))
            {
                players.Remove(username);
            }
        }

        public string GetMazeJsonString(int width,int height)
        {
            MazeGeneratorSoapClient client=new MazeGeneratorSoapClient();
            JavaScriptSerializer ser = new JavaScriptSerializer();
            return ser.Serialize(client.GenerateNewMaze_XML(height, width));
        }

    }
}
